package org.jeecg.modules.demo.mes.controller;

import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.demo.mes.entity.CamelliaMesExtraTechParams;
import org.jeecg.modules.demo.mes.entity.CamelliaMesProduct;
import org.jeecg.modules.demo.mes.entity.MesOptimize;
import org.jeecg.modules.demo.mes.service.ICamelliaMesExtraTechParamsService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.demo.mes.service.ICamelliaMesProductService;
import org.jeecg.modules.demo.mes.service.IMesOptimizeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 萃取工艺管理
 * @Author: jeecg-boot
 * @Date: 2023-02-03
 * @Version: V1.0
 */
@Api(tags = "萃取工艺管理")
@RestController
@RequestMapping("/mes/camelliaMesExtraTechParams")
@Slf4j
public class CamelliaMesExtraTechParamsController extends JeecgController<CamelliaMesExtraTechParams, ICamelliaMesExtraTechParamsService> {
    @Autowired
    private ICamelliaMesExtraTechParamsService camelliaMesExtraTechParamsService;


    @Autowired
    private IMesOptimizeService optimizeService;

    @Autowired
    private ICamelliaMesProductService productService;

    /**
     * 分页列表查询
     *
     * @param camelliaMesExtraTechParams
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "萃取工艺管理-分页列表查询")
    @ApiOperation(value = "萃取工艺管理-分页列表查询", notes = "萃取工艺管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<CamelliaMesExtraTechParams>> queryPageList(CamelliaMesExtraTechParams camelliaMesExtraTechParams,
                                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                   HttpServletRequest req) {
        QueryWrapper<CamelliaMesExtraTechParams> queryWrapper = QueryGenerator.initQueryWrapper(camelliaMesExtraTechParams, req.getParameterMap());
        Page<CamelliaMesExtraTechParams> page = new Page<CamelliaMesExtraTechParams>(pageNo, pageSize);
        IPage<CamelliaMesExtraTechParams> pageList = camelliaMesExtraTechParamsService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    class Optimize {
        double temp;
        int times;
    }

    public Optimize optimize(MesOptimize mesOptimize) throws Exception{
        Optimize optimize =new Optimize();
        String[][] table1 = {
                {"水平", "萃取次数", "萃取温度", "萃取时间", "料液比"},
                {"1", "2", "35", "35", "1:1.5"},
                {"1", "3", "40", "40", "1:2.0"},
                {"1", "4", "45", "45", "1:2.5"}
        };
        table1[1][1] = mesOptimize.getAttempt1();
        table1[2][1] = mesOptimize.getAttempt2();
        table1[3][1]= mesOptimize.getAttempt3();
        table1[1][2] = mesOptimize.getTemp1();
        table1[2][2] = mesOptimize.getTemp2();
        table1[3][2]= mesOptimize.getTemp3();

        table1[1][3] = mesOptimize.getTime1();
        table1[2][3] = mesOptimize.getTime2();
        table1[3][3]= mesOptimize.getTime3();

        table1[1][4] = mesOptimize.getRatio1();
        table1[2][4] = mesOptimize.getRatio2();
        table1[3][4]= mesOptimize.getRatio3();


        double[][] table2 = {
                {1, 1, 1, 1, 1, 85.27},
                {2, 1, 2, 2, 2, 88.41},
                {3, 1, 3, 3, 3, 87.26},
                {4, 2, 1, 2, 3, 89.35},
                {5, 2, 2, 3, 1, 92.21},
                {6, 2, 3, 1, 2, 91.84},
                {7, 3, 1, 3, 2, 93.21},
                {8, 3, 2, 1, 3, 95.21},
                {9, 3, 3, 2, 1, 94.77}
        };

        table2[0][5] = mesOptimize.getRate1();
        table2[1][5] = mesOptimize.getRate2();
        table2[2][5] = mesOptimize.getRate3();
        table2[3][5] = mesOptimize.getRate4();
        table2[4][5] = mesOptimize.getRate5();
        table2[5][5] = mesOptimize.getRate6();
        table2[6][5] = mesOptimize.getRate7();
        table2[7][5] = mesOptimize.getRate8();
        table2[8][5] = mesOptimize.getRate9();

        double[][] k = new double[table1.length - 1][table1[0].length - 1];

        for (int j = 1; j < table2[0].length; j++) {
            for (int i = 0; i < table2.length; i++) {
                // val =行
                // 列= 列+1
                if (j == table2[0].length - 1) continue;
                k[(int) table2[i][j] - 1][j - 1] += table2[i][table2[0].length - 1];
            }
        }

        for (int i = 0; i < k.length; i++) {
            for (int j = 0; j < k[0].length; j++) {
                k[i][j] /= 3;
                System.out.printf("%.2f  ", k[i][j]);
            }
            System.out.println();
        }

        double[] R = new double[k[0].length];

        for (int j = 0; j < k[0].length; j++) {
            double min = Integer.MAX_VALUE;
            double max = Integer.MIN_VALUE;
            for (int i = 0; i < k.length; i++) {
                min = Math.min(min, k[i][j]);
                max = Math.max(max, k[i][j]);
            }
            R[j] = max - min;
        }

        for (int j = 0; j < k[0].length; j++) {
            System.out.printf("%.2f  ", R[j]);
        }

        Integer[] rankR = new Integer[k[0].length];
        for (int i = 0; i < rankR.length; i++) {
            rankR[i] = i;
        }
        Arrays.sort(rankR, (i, j) -> {
            return -Double.compare(R[i], R[j]);
        });
        System.out.println();
        System.out.println("影响率主次排序：");
        for (int i = 0; i < k[0].length; i++) {
            System.out.print(table1[0][rankR[i] + 1] + " ");
        }
        System.out.println();
        System.out.println("工艺参数最佳组合为：");

        for (int i = 0; i < k[0].length; i++) {
            System.out.print(table1[0][rankR[i] + 1] + " ");
        }
        System.out.println();
        for (int i = 0; i < k[0].length; i++) {
            int l = 0;
            double max = 0;
            for (int j = 0; j < k.length; j++) {
                if (k[j][rankR[i]] > max) {
                    max = k[j][rankR[i]];
                    l = j;
                }
            }
            System.out.print(table1[l + 1][rankR[i] + 1] + "      ");
        }
        double temp = 0;
        int times = 0;
        for (int i = 0; i < k[0].length; i++) {
            int l = 0;
            double max = 0;
            for (int j = 0; j < k.length; j++) {
                if (k[j][rankR[i]] > max) {
                    max = k[j][rankR[i]];
                    l = j;
                }

            }
//                System.out.print(table1[l+1][rankR[i] + 1]+"      ");
        }
        System.out.println();
        double max = 0;
        int l = 0;
        for (int i = 0; i < k.length; i++) {
            if (k[i][0] > max) {
                max = k[i][0];
                l = i;
            }
        }
        System.out.println(table1[l + 1][1]);
        times = Integer.parseInt(table1[l + 1][1]);
        max = 0;
        l = 0;
        for (int i = 0; i < k.length; i++) {
            if (k[i][1] > max) {
                max = k[i][1];
                l = i;
            }
        }
        System.out.println(table1[l + 1][2]);

        temp = Double.parseDouble(table1[l + 1][2]);
        optimize.setTemp(temp);
        optimize.setTimes(times);
        return optimize;
    }


    @ApiOperation(value = "优化", notes = "优化")
    @GetMapping(value = "/optimize")
    public Result<Optimize> queryPageList(@RequestParam(name = "id") String id) {

        List<MesOptimize> list = optimizeService.list();
        for (MesOptimize mesOptimize : list) {
            if (mesOptimize.getProductId().equals(id)) {
                try {
                    Optimize optimize1 = optimize(mesOptimize);
                    return Result.OK("优化完成",optimize1);
                } catch (Exception e) {
                    return Result.error("优化错误，优化记录有异常");
                }
            }
        }
            return Result.error("无匹配得优化记录");

    }

    /**
     * 添加
     *
     * @param camelliaMesExtraTechParams
     * @return
     */
    @AutoLog(value = "萃取工艺管理-添加")
    @ApiOperation(value = "萃取工艺管理-添加", notes = "萃取工艺管理-添加")
    //@RequiresPermissions("org.jeecg.modules.demo:camellia_mes_extra_tech_params:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody CamelliaMesExtraTechParams camelliaMesExtraTechParams) {

        CamelliaMesExtraTechParams obj = camelliaMesExtraTechParams;
        Double aDouble = 0.0;
//		aDouble = Double.valueOf(obj.getAminoAcid());
//		if(aDouble>100||aDouble<0){
//			return Result.error("百分比数值错误");
//		}

        camelliaMesExtraTechParamsService.save(camelliaMesExtraTechParams);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param camelliaMesExtraTechParams
     * @return
     */
    @AutoLog(value = "萃取工艺管理-编辑")
    @ApiOperation(value = "萃取工艺管理-编辑", notes = "萃取工艺管理-编辑")
    //@RequiresPermissions("org.jeecg.modules.demo:camellia_mes_extra_tech_params:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody CamelliaMesExtraTechParams camelliaMesExtraTechParams) {
        CamelliaMesExtraTechParams obj = camelliaMesExtraTechParams;

        camelliaMesExtraTechParamsService.updateById(camelliaMesExtraTechParams);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "萃取工艺管理-通过id删除")
    @ApiOperation(value = "萃取工艺管理-通过id删除", notes = "萃取工艺管理-通过id删除")
    //@RequiresPermissions("org.jeecg.modules.demo:camellia_mes_extra_tech_params:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        camelliaMesExtraTechParamsService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "萃取工艺管理-批量删除")
    @ApiOperation(value = "萃取工艺管理-批量删除", notes = "萃取工艺管理-批量删除")
    //@RequiresPermissions("org.jeecg.modules.demo:camellia_mes_extra_tech_params:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.camelliaMesExtraTechParamsService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "萃取工艺管理-通过id查询")
    @ApiOperation(value = "萃取工艺管理-通过id查询", notes = "萃取工艺管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<CamelliaMesExtraTechParams> queryById(@RequestParam(name = "id", required = true) String id) {
        CamelliaMesExtraTechParams camelliaMesExtraTechParams = camelliaMesExtraTechParamsService.getById(id);
        if (camelliaMesExtraTechParams == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(camelliaMesExtraTechParams);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param camelliaMesExtraTechParams
     */
    //@RequiresPermissions("org.jeecg.modules.demo:camellia_mes_extra_tech_params:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CamelliaMesExtraTechParams camelliaMesExtraTechParams) {
        return super.exportXls(request, camelliaMesExtraTechParams, CamelliaMesExtraTechParams.class, "萃取工艺管理");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("camellia_mes_extra_tech_params:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CamelliaMesExtraTechParams.class);
    }


}
